<template>
  <s-layout title="往期每日中奖名单">
    <view class="lottery-container">
      <view class="lottery">
        <view 
          class="lottery-header"
          :style="{ top: sheep.$platform.device.statusBarHeight + 44 + 'px' }">
          <view class="lottery-header-date" @click="handleStageToggle" v-if="currentStageTitle">
            <view class="current-date">{{ currentStageTitle }}</view>
            <view class="icon">
               <image
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250326/16e461094104d8883c2d8005ccfd8fca.png"
                mode="widthFix"
              />
            </view>
          </view>
          <view class="lottery-header-serach">
            <view class="search-box">
              <input
                type="text"
                class="search-input"
                @confirm="handleInputSearch"
                v-model="lotteryParams.keyword"
                placeholder="搜索手机号/用户昵称"
              />
              <view class="search-btn" @click="handleInputSearch">搜索</view>
            </view>
            <view class="filter-box" @click="handlePrizeToggle">
              <view>
                <image
                  src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250326/574748210e349c0ccbe0b3a0f348effc.png"
                  mode="widthFix"
                />
              </view>
            </view>
          </view>
        </view>
        <view class="lottery-body">
          <view class="list">
            <view class="list-item" v-for="item in state.lotteryList" :key="item.user_id">
              <view class="user">{{ item.user.nickname }}</view>
              <view class="phone">{{ formatPhone(item.user.mobile) }}</view>
              <view class="prize">{{ item.product_name }}</view>
              <view class="time">{{ item.create_time }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 期数弹窗 -->
      <view class="date-picker-box">
        <uni-popup 
          ref="stagePopupRef" 
          :duration="300"
          :mask-click="true"
          background-color="#fff"
        >
          <view class="popup-content">
            <view class="popup-header">
              <text class="cancel" @tap="handleStageClose">关闭</text>
              <text class="confirm" @tap="handleStageConfirm">选择</text>
            </view>
            <view class="picker">
              <picker-view  
                class="picker-view" 
                :value="stageVal" 
                @change="handleStageChange"
              >
                <picker-view-column>
                  <view class="item" v-for="item in state.stageArr" :key="item.id">{{ item.title }}</view>
                </picker-view-column>
              </picker-view>
            </view>
          </view>
        </uni-popup>
      </view>

      <!-- 奖品弹窗 -->
      <view class="date-picker-box">
        <uni-popup 
          ref="prizePopupRef" 
          :duration="300"
          :mask-click="true"
          background-color="#fff"
        >
          <view class="popup-content">
            <view class="popup-header" >
              <text class="cancel" @tap="handlePrizeClose">关闭</text>
              <text class="confirm" @tap="handlePrizeConfirm">选择</text>
            </view>
            <view class="picker">
              <picker-view 
                class="picker-view" 
                :value="prizeVal" 
                @change="handlePrizeChange"
              >
                <picker-view-column>
                  <view class="item" v-for="item in state.prizeArr" :key="item.id">{{ item.name }}</view>
                </picker-view-column>
              </picker-view>
            </view>
          </view>
        </uni-popup>
      </view>
    </view>

    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无中奖名单"></s-empty>
  </s-layout>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';

  import sheep from '@/sheep';
  // 状态定义
  let state = reactive({
    lotteryList: [],
    stageArr: [],
    prizeArr: [],
    pagination: {
      current_page: 1,
      last_page: 1,
      total: 0,
    },
    loadStatus: '', // 加载更多状态 ['more' | 'noMore']
  });

  let lotteryParams = reactive({
    page: 1,
    list_rows: 20, // 每页20条数据
    id: '0', // 期数id
    product_id: '', // 奖品id
    keyword: '', // 模糊匹配关键字
  })

  let prizeVal = reactive([0]) // 回显奖品picker
  let prizeID = ref('') // 暂时保存奖品id，在picker change的时候

  let stageVal = reactive([0]) // 回显期数picker
  let stageID = ref('') // 暂时保存期数id，在picker change的时候

  const stagePopupRef = ref(null)
  const prizePopupRef = ref(null)

  const currentStageTitle = ref('') // 当前期数title
  const indicatorStyle = ref(`height: 40rpx;`)

  const resetData = () => {
    state.lotteryList = []
    state.pagination = {
      current_page: 1,
      last_page: 1,
      total: 0
    }
    state.loadStatus = ''
    lotteryParams.page = 1
  }

  const handlePrizeChange = (e) => {
    const val = e.detail.value
    console.log(val[0])
    console.log(typeof state.prizeArr[val[0]].id)
    console.log(state.prizeArr[val[0]].id, 'prizeArrid')
    prizeID.value = Number(state.prizeArr[val[0]].id)
    prizeVal = val
   
    console.log(prizeVal, 'prizeVal=====')
    console.log(typeof prizeVal, 'prizeVal=====')
  }
  const handlePrizeConfirm = () => {
    lotteryParams.product_id = prizeID.value
    resetData()
    getPrevLotteryRecord()
    handlePrizeClose()
  }

  const handleStageChange = (e) => {
    const val = e.detail.value
    console.log(val[0])
    console.log(typeof state.stageArr[val[0]].id)
    console.log(state.stageArr[val[0]].id, 'stageArrid')
    stageID.value = Number(state.stageArr[val[0]].id)
    stageVal = val
   
    console.log(stageVal, 'prizeVal=====')
  }
  const handleStageConfirm = () => {
    lotteryParams.id = stageID.value
    resetData()
    getPrevLotteryRecord()
    handleStageClose()
  }

  // 搜索框
  const handleInputSearch = () => {
    resetData()
    getPrevLotteryRecord()
  }

  // 获取奖品档期select
  const getLotteryStage = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotteryuserDayPeriods()
      console.log(error,'error')
      console.log(data,'获取奖品档期select')
      if (error == 0) {
        state.stageArr = data

        console.log(data,'获取奖品档期select')
        currentStageTitle.value = data[0]?.title
        lotteryParams.id = data[0]?.id
        stageID.value = data[0]?.id
        return data
      }
    } catch (error) {
      console.error('获取奖品档期select失败:', error)
      throw error // 抛出错误以便上层捕获
    }
  }

  // 往期中奖名单
  const getPrevLotteryRecord = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotteryuserDayopenLog(lotteryParams)
      if (error == 0) {
        const { total, current_page, last_page } = data
        state.lotteryList = [...state.lotteryList, ...data.data]

        Object.assign(state.pagination, { total, current_page, last_page })

        if (state.pagination.current_page < state.pagination.last_page) {
          state.loadStatus = 'more';
        } else {
          state.loadStatus = 'noMore';
        }

        console.log(data, '用户中奖名单')
        return data.data
      }
    } catch (error) {
      throw error
    }
  }

  // 获取奖池中的奖品记录
  const getPoolLotteryList = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotteryuserDaypool()
      // const { error, data } = await sheep.$api.tuangou.getPoolLotteryList()
      if (error == 0) {
        state.prizeArr = data
        return data
      }
    } catch (e) {
       throw error
    }
  }

  const loadmore = () => {
    if (state.loadStatus !== 'noMore') {
      state.pagination.current_page ++ 
      lotteryParams.page ++ 
      getPrevLotteryRecord();
    }
  }

  onLoad(async () => {
    // 往期select
    await getLotteryStage()
    // 往期中奖名单
    await getPrevLotteryRecord()
    // 获取奖池中的奖品记录
    await getPoolLotteryList()
  });

  onReachBottom(() => {
    console.log('触底了。')
     loadmore()
  });
   
  const handleStageToggle = () => {
    stagePopupRef.value.open('bottom')
  }
  const handleStageClose = () => {
    stagePopupRef.value?.close()
  }

  const handlePrizeToggle = () => {
    prizePopupRef.value.open('bottom')
  }
  const handlePrizeClose = () => {
    prizePopupRef.value?.close()
  }

  /**
   * @description 将手机号****隐藏部分号码
   * @param phone 手机号
   */
  const formatPhone = (phone) => {
    if (!phone || phone.length !== 11) return phone
    return phone.substring(0, 3) + '****' + phone.substring(7)
  }

</script>

<style lang="less" scoped>
.lottery-container {
  background-color: #f2f3f6;
  .lottery {
    &-header {
      box-sizing: border-box;
      background-color: #fff;
      position: sticky;
      box-shadow: 0 4px 6px -6px rgba(0, 0, 0, 0.3);
      &-date {
        display: flex;
        align-items: center;
        height: 80rpx;
        padding: 0 16rpx;

        .current-date {
          background: linear-gradient(270deg, #EA250D 0%, #EF6C1C 100%);
          -webkit-background-clip: text; /* 对于WebKit浏览器（如Safari和Chrome） */
          background-clip: text;
          -webkit-text-fill-color: transparent; /* 使用背景剪裁填充文本颜色 */
        }
        .icon {
          width: 27rpx;
          height: 27rpx;
          margin-top: 2rpx;
          margin-left: 12rpx;
          image {
            width: 100%;
          }
        }
      }
      &-serach {
        background-color: #fff;
        border-top: 2rpx solid #f2f3f6;
        display: flex;
        justify-content: space-between;
        padding: 12rpx 0 10rpx 16rpx;
        .search-box {
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .search-box {
          position: relative;
          padding: 4rpx; /* 为渐变边框预留空间 */
          border-radius: 40rpx;
          background: linear-gradient(270deg, #CD352A 0%, #F8533F 100%);
        }

        .search-box::before {
          content: '';
          position: absolute;
          top: 2rpx;
          left: 2rpx;
          right: 2rpx;
          bottom: 2rpx;
          background: white;
          border-radius: 38rpx;
        }

        .search-input {
          position: relative;
          border: none;
          border-radius: 40rpx;
          outline: none;
          font-size: 24rpx;
          background: transparent;
          flex: 1;
          padding-left: 24rpx;
          padding-right: 124rpx;
        }
        .search-input::placeholder {
          color: #BFBFBF !important;
        }

        .search-btn {
          position: absolute;
          right: 8rpx;
          top: 9rpx;
          bottom: 6rpx;
          border: none;
          border-radius: 40rpx;
          width: 100rpx;
          height: 50rpx;
          background: linear-gradient(270deg, #EA250D 0%, #EF6C1C 100%);
          color: white;
          font-size: 24rpx;
          cursor: pointer;
          transition: background-color 0.3s;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        
        .filter-box {
          width: 110rpx;
          height: 60rpx;
          border: 2rpx solid #B5B5B5;
          border-right: none;
          border-top-left-radius: 40rpx;
          border-bottom-left-radius: 40rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-left: 12rpx;
          & > view {
            image {
              width: 32rpx;
            }
          }
        }
      }
    }
    &-body {
      .list {
        margin: 20rpx 10rpx;
        &-item {
          background-color: #fff;
          margin-bottom: 10rpx;
          padding: 16rpx 26rpx;
          box-sizing: border-box;

          display: grid;
          grid-template-columns: 1fr 1.5fr 1fr 2fr;  /* 调整每列的宽度比例 */
          align-items: center;
          gap: 4rpx;
          
          view {
            font-size: 22rpx;
            color: #3D3D3D;
            font-weight: 500;
          }
          .user {
            max-width: 120rpx;
            white-space: nowrap; /* 禁止换行 */
            overflow: hidden; /* 隐藏超出容器的内容 */
            text-overflow: ellipsis; /* 将溢出部分显示为省略号 */
          }
          .time {
            text-align: right; 
            padding-right: 0;
          }
        }
      }
    }
  }
}

.popup-content {
  height: 400rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  .cancel, .confirm {
    color: #3D3D3D;
    font-size: 28rpx;
    font-weight: 700;
  }
}

.picker {
  width: 100%;
  text-align: center;
  background-color: #fff;
  .picker-view {
    height: 242rpx;
    padding-bottom: 18rpx;
  }
}

.uni-input {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
}
</style>
